<?php
/**
 *
 * @author Strawberry🍓
 * @date 2021-06-25 2:15 下午
 *
 */

$host = '120.92.105.112';
$port = '8804';
$data = [
    'TradeCode'=> '',
    'TradeTime'=>date('YmdHis'),
    'BankID'=>'',
    'TermType'=>'',
    'TermID'=>'',
    'ClientID'=>'',
    'UserID'=>'',
    'PaySerialNo'=>'',
    'Amount'=>'',
];
$message = arrayToXml($data);
var_dump($message);


function send_tcp_message($host, $port, $message)
{
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    @socket_connect($socket, $host, $port);

    $num = 0;
    $length = strlen($message);
    do
    {
        $buffer = substr($message, $num);
        $ret = @socket_write($socket, $buffer);
        $num += $ret;
    } while ($num < $length);
    $ret = '';
    do
    {
        $buffer = @socket_read($socket, 1024, PHP_BINARY_READ);
        $ret .= $buffer;
    } while (strlen($buffer) == 1024);
    socket_close($socket);
    return $ret;
}


function arrayToXml($arr,$dom=0,$item=0){
    if (!$dom){
        $dom = new DOMDocument("1.0");
    }
    if(!$item){
        $item = $dom->createElement("root");
        $dom->appendChild($item);
    }
    foreach ($arr as $key=>$val){
        $itemx = $dom->createElement(is_string($key)?$key:"item");
        $item->appendChild($itemx);
        if (!is_array($val)){
            $text = $dom->createTextNode($val);
            $itemx->appendChild($text);

        }else {
            arrayToXml($val,$dom,$itemx);
        }
    }
    return $dom->saveXML();
}


function xmlToArray($xml){
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    $val = json_decode(json_encode($xmlstring),true);
    return $val;
}

$ret = send_tcp_message($host, $port, $message);